package com.springboot.consumer.dao;


import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.springboot.consumer.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author XiaoLuo
 * @ClassName: UserDao
 * @Description: ${todo}
 * @date 2019/4/6 21:22
 */
@Component
public class UserDao {
    @Autowired
    private RestTemplate restTemplate;

//    @Autowired
//    private DiscoveryClient discoveryClient; //Eureka客户端，可以获取到服务实例信息

    private static final Logger LOGGER = LoggerFactory.getLogger(UserDao.class);



//声明一个失败回滚处理函数queryUserByIdFallback，当queryUserById执行超时（默认是1000毫秒），就会执行fallback函数，返回错误提示
    @HystrixCommand(fallbackMethod = "queryUserByIdFallback")
    public User queryUserById(Long id){



//        String url = "http://localhost:8081/user/"+id;
//        根据服务名称，获取服务实例
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//        因为只有一个UserService，因此我们直接get(0)获取
//        ServiceInstance instance = instances.get(0);
//        获取IP和端口号
//        String url = "http://"+instance.getHost()+":"+instance.getPort()+"/user/"+id;

        long begin = System.currentTimeMillis();
//        地址直接写服务名称即可
        String url = "http://user-service/user/"+id;
        User user = this.restTemplate.getForObject(url, User.class);

        long end = System.currentTimeMillis();
        // 记录访问用时：
        LOGGER.info("访问用时：{}", end - begin);
//        多次查询，每隔500毫秒
//        try {
//            Thread.sleep(500);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        return user;
    }

    public User queryUserByIdFallback(Long id){
        User user = new User();
        user.setId(id);
        user.setName("用户信息查询出现异常！");
        return user;
    }

}
